#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>
#include <unistd.h>
#include <poll.h>

using namespace std;

int main()
{
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd < 0) {
        cerr << "Create socket error!";
    }

    const int port = 7000;
    struct sockaddr_in s_addr;
    bzero(&s_addr, sizeof(s_addr));
    s_addr.sin_family = AF_INET;
    s_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    s_addr.sin_port = htons(port);
    int bret = bind(sfd, (struct sockaddr*)&s_addr, sizeof(s_addr));
    if (bret < 0) {
        cerr << "Bind error: " << bret << endl;;
    }
    cout << "binding at " << port << endl;

    listen(sfd, 10);

    struct sockaddr c_addr;
    socklen_t len;
    char buffer[1024];

    int cfd = accept(sfd, &c_addr, &len);
    cout << "Accept!" << endl;
    struct pollfd poll_arry[1] = {{cfd, POLLIN}};
    while (true) {
        poll(poll_arry, 1, 0);
        if (poll_arry[0].revents == POLLIN){
            cout << "Got one" << endl;
            bzero(buffer, 1024);
            int rsize = read(cfd, buffer, 1024);
            cout << "Read size: " << rsize << endl;
            cout << "Content: " << buffer << endl;
            write(cfd, "Got it\n", 7);
        }
    }
    close(cfd);
    close(sfd);
    return 0;
}

